package com.brilliance.project.common.report;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.j2ee.servlets.BaseHttpServlet;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.brilliance.project.common.exception.BaseJasperReportException;
import com.brilliance.project.common.exception.ErrorReferenceReport;

/**
 * Page/class Name: PdfReportExportImpl<br />
 * Title: 导出 Pdf 报表<br />
 * Description: 导出 Pdf 报表<br />
 * Copyright: Copyright(c) brilliance Technology.<br />
 * 
 * @author HLJ
 * @version 1.0
 * @created 2012/11/26
 */
public class PdfReportExportImpl implements IBaseReportExport {
	private static Log log = LogFactory.getLog(PdfReportExportImpl.class);
	public String jasperreportFilePath = null;
	public List<String> jasperreportFilePaths = null;

	public void setJasperreportFilePath(String jasperreportFilePath) {
		this.jasperreportFilePath = jasperreportFilePath;
	}

	public void setJasperreportFilePaths(List<String> jasperreportFilePaths) {
		this.jasperreportFilePaths = jasperreportFilePaths;
	}

	/**
	 * 导出报表
	 * 
	 * @param request
	 * @param response
	 * @param jasperPrint
	 * @param fileNam
	 * @throws Exception
	 */
	public void export(HttpServletRequest request,
			HttpServletResponse response, JasperPrint jasperPrint,
			String fileName) {
		// TODO Auto-generated method stub
		OutputStream outputStream = null;

		try {
			outputStream = response.getOutputStream();
		} catch (IOException ioe) {
			ioe.printStackTrace();
			log.error(ioe.toString());
			// 从Response中取得OutputStream时发生错误
			throw new BaseJasperReportException(
					ErrorReferenceReport.RESPONSE_GET_OUTPUTSTREAM_ERROR);
		} /* end of try ... catch */

		try {
			// response.setContentType(ReportConstant.CONTENT_TYPE_HTML);
			response.setContentType(ReportConstant.CONTENT_TYPE_PDF);
			response.setCharacterEncoding(ReportConstant.CHARACTER_ENCODING_UTF_8);

			if (fileName == null || fileName.equals("")) {
				response.setHeader(ReportConstant.HEADER_CONTENT,
						ReportConstant.HEADER_INLINE + fileName);
			} /* end of if */

			// 使用JRPdfExproter导出pdf报表
			JRPdfExporter exporter = new JRPdfExporter();
			exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
			exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
					outputStream);
			exporter.exportReport();
		} catch (Exception ex) {
			log.error(ex.toString());
			ex.printStackTrace();
			throw new BaseJasperReportException(
					ErrorReferenceReport.RESPONSE_GET_PRINTWRITER_ERROR);
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException ex) {
					log.error(ex.toString());
					ex.printStackTrace();
				}
			} /* end of if */
		} /* end of try ... catch ... finally */
	}

	/**
	 * 
	 * @param request
	 * @param response
	 * @param jasperPrint
	 * @param fileNam
	 * @throws Exception
	 */
	public void view(HttpServletRequest request, HttpServletResponse response,
			Map params, JRDataSource dataSource, String fileName) {
		// TODO Auto-generated method stub
		OutputStream outputStream = null;
		try {
			outputStream = response.getOutputStream();
		} catch (IOException ioe) {
			ioe.printStackTrace();
			log.error(ioe.toString());
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (Exception ex) {
					log.error(ex.toString());
					ex.printStackTrace();
				}
			} /* end of if */
			// 从Response中取得OutputStream时发生错误
			throw new BaseJasperReportException(
					ErrorReferenceReport.RESPONSE_GET_OUTPUTSTREAM_ERROR);
		} /* end of try ... catch */

		try {
			JasperPrint jasperPrint = new GenerateJasperPrint(request
					.getSession().getServletContext()
					.getRealPath(jasperreportFilePath), params, dataSource)
					.getJasperPrint();
			// 将填充完的japserPrint放入session中。
			request.getSession().setAttribute(
					BaseHttpServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,
					jasperPrint);
			// 取得japserPrintList
			List jasperPrintList = BaseHttpServlet.getJasperPrintList(request);

			if (jasperPrintList == null) {
				throw new BaseJasperReportException(
						"在Http Session中没有找到JasperPrint List");
			} /* end of if */

			response.setContentType(ReportConstant.CONTENT_TYPE_PDF);
			response.setCharacterEncoding(ReportConstant.CHARACTER_ENCODING_UTF_8);

			response.setHeader(
					ReportConstant.HEADER_CONTENT,
					ReportConstant.HEADER_ATTACHMENT_INLINE
							+ URLEncoder.encode(fileName,
									ReportConstant.CHARACTER_ENCODING_UTF_8)
							+ ReportConstant.HEADER_ATTACHMENT_PDF);

			// 使用JRPdfExproter导出pdf
			JRPdfExporter exporter = new JRPdfExporter();
			// 设置JasperPrintList
			exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST,
					jasperPrintList);
			exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
					outputStream);
			exporter.exportReport();
		} catch (Exception ex) {
			log.error(ex.toString());
			ex.printStackTrace();
			throw new BaseJasperReportException(
					ErrorReferenceReport.CAN_NOT_RUN_REPORT_TO_PDF_STREAM);
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (Exception ex) {
					log.error(ex.toString());
					ex.printStackTrace();
				} /* end of try catch */
			} /* end of if */
		} /* end of try ... catch ... finally */
	}

	/**
	 * 
	 */
	public void viewList(HttpServletRequest request,
			HttpServletResponse response, Map params,
			List<? extends JRDataSource> dataSourceList, String fileName) {
		OutputStream outputStream = null;
		try {
			outputStream = response.getOutputStream();
		} catch (IOException ioe) {
			ioe.printStackTrace();
			log.error(ioe.toString());
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (Exception ex) {
					log.error(ex.toString());
					ex.printStackTrace();
				}
			} /* end of if */
			// 从Response中取得OutputStream时发生错误
			throw new BaseJasperReportException(
					ErrorReferenceReport.RESPONSE_GET_OUTPUTSTREAM_ERROR);
		} /* end of try ... catch */

		try {
			List<JasperPrint> jasperPrints = new ArrayList<JasperPrint>();
			for (int i = 0; i < jasperreportFilePaths.size(); i++) {
				String filePath = jasperreportFilePaths.get(i);
				jasperPrints.add(new GenerateJasperPrint(request.getSession()
						.getServletContext().getRealPath(filePath), params,
						dataSourceList.get(i)).getJasperPrint());
			}

			// request.getSession().setAttribute(BaseHttpServlet.DEFAULT_JASPER_PRINT_LIST_SESSION_ATTRIBUTE,
			// jasperPrints);
			// //取得japserPrintList
			// List jasperPrintList =
			// BaseHttpServlet.getJasperPrintList(request);
			// if (jasperPrintList == null) {
			// throw new
			// BaseJasperReportException("在Http Session中没有找到JasperPrint List");
			// } /* end of if */

			response.setContentType(ReportConstant.CONTENT_TYPE_PDF);
			response.setCharacterEncoding(ReportConstant.CHARACTER_ENCODING_UTF_8);

			response.setHeader(
					ReportConstant.HEADER_CONTENT,
					ReportConstant.HEADER_ATTACHMENT
							+ URLEncoder.encode(fileName,
									ReportConstant.CHARACTER_ENCODING_UTF_8)
							+ ReportConstant.HEADER_ATTACHMENT_PDF);

			/* JasperExportManager.exportReportToPdfStream只支持单jasperPrint输出 */
			// for(JasperPrint jasperPrint:jasperPrints){
			// JasperExportManager.exportReportToPdfStream(jasperPrint,
			// outputStream);
			// }

			// 使用JRPdfExproter导出pdf
			JRPdfExporter exporter = new JRPdfExporter();
			// 设置JasperPrintList
			// exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST,
			// jasperPrintList);
			exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST,
					jasperPrints);
			exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
					outputStream);
			exporter.exportReport();
		} catch (Exception ex) {
			log.error(ex.toString());
			ex.printStackTrace();
			throw new BaseJasperReportException(
					ErrorReferenceReport.CAN_NOT_RUN_REPORT_TO_PDF_STREAM);
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (Exception ex) {
					log.error(ex.toString());
					ex.printStackTrace();
				} /* end of try catch */
			} /* end of if */
		} /* end of try ... catch ... finally */
	}

	@Override
	public void export(final JasperPrint jasperPrint, final String fileName) {
		OutputStream outputStream = null;

		try {
			outputStream = new FileOutputStream(fileName);
		} catch (FileNotFoundException e) {
			throw new BaseJasperReportException(
					ErrorReferenceReport.RESPONSE_GET_OUTPUTSTREAM_ERROR, e);
		}

		try {
			// 使用JRPdfExproter导出pdf报表
			JRPdfExporter exporter = new JRPdfExporter();
			exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
			exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
					outputStream);
			exporter.exportReport();
		} catch (Exception ex) {
			log.error(ex.toString(), ex);
			throw new BaseJasperReportException(
					ErrorReferenceReport.RESPONSE_GET_PRINTWRITER_ERROR, ex);
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException ex) {
					log.error(ex.toString(), ex);
				}
			} /* end of if */
		} /* end of try ... catch ... finally */
	}

	@Override
	public void export(List<JasperPrint> jasperPrintList, String fileName,
			String[] sheetNames) {
		OutputStream outputStream = null;

		try {
			outputStream = new FileOutputStream(fileName);
		} catch (FileNotFoundException e) {
			throw new BaseJasperReportException(
					ErrorReferenceReport.RESPONSE_GET_OUTPUTSTREAM_ERROR, e);
		}

		try {
			// 使用JRPdfExproter导出pdf报表
			JRPdfExporter exporter = new JRPdfExporter();
			exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST,
					jasperPrintList);
			exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
					outputStream);
			exporter.exportReport();
		} catch (Exception ex) {
			log.error(ex.toString(), ex);
			throw new BaseJasperReportException(
					ErrorReferenceReport.RESPONSE_GET_PRINTWRITER_ERROR, ex);
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException ex) {
					log.error(ex.toString(), ex);
				}
			} /* end of if */
		} /* end of try ... catch ... finally */
	}

	@Override
	public InputStream exportForInputStream(JasperPrint jasperPrint,
			String fileName) {
		// TODO Auto-generated method stub
		return null;
	}

}
